﻿using System;

using System.Collections.Generic;
using System.Text;
using Silvermoon.Visuals;
using Silvermoon.Images;
using System.Drawing;
using Silvermoon.Core;

namespace Silvermoon.Controls
{
    /// <summary>
    /// An animated busy control to present busy states.
    /// </summary>
    public class BusyControl : Control
    {

        private RotateTransform rotate;
        private ImageVisual visual;
        private int t0;

        public BusyControl()
            : base()
        {
            ShowDelay = 500;
            visual = new ImageVisual { Image = SysImages.Busy, Visible = false };
            rotate = new RotateTransform { Angle = 0, Axis = RotateAxis.ZAxis };
            Transformations = new Transformation[] { rotate };
            this.Size = Control.ScaledSize(64, 64); 
            Visuals = new Visual[] { visual };
            OnEnabledChanged();
        }

        public override void Dispose()
        {
            Screen.Current.Tick -= OnTick;
            visual.Dispose();
            Visuals = null;
            base.Dispose();
        }

        protected float Angle
        {
            get { return rotate.Angle; }
            set
            {
                if (rotate.Angle != value)
                {
                    rotate.Angle = value;
                    Invalidate(InvalidationFlag.Appearance);
                }
            }
        }

        public int ShowDelay { get; set; }

        protected override void OnEnabledChanged()
        {
            if (Enabled)
            {
                t0 = Environment.TickCount;
                Screen.Current.Tick += new EventHandler<TimeEventArgs>(OnTick);
            }
            else
            {
                Screen.Current.Tick -= OnTick;
                visual.Visible = false;
            }
            base.OnEnabledChanged();
        }

        protected override void OnLayout()
        {
            visual.Size = Size;
            base.OnLayout();
        }

        void OnTick(object sender, TimeEventArgs e)
        {
            if ((e.Tick - t0) > ShowDelay) visual.Visible = true;
            int angle = (e.Tick / 4) % 360;
            Angle = (float)angle;
        }

    }
}
